



const { io } = require('../app');
const userSockets = new Map(); // 存储用户ID与Socket ID的映射
const chatHistory = new Map(); // 存储每个对话的历史消息（可选）
const { chatRecordModel } = require('../model/model');

io.on('connection', (socket) => {
    console.log('新客户端连接，Socket ID:', socket.id);

    // ---------------------- 用户登录逻辑 ----------------------
    socket.on('login', (userId) => {
        // 存储用户ID和Socket ID的映射
        userSockets.set(userId, socket.id);
        console.log(`用户 ${userId} 登录，Socket ID: ${socket.id}`);
    });

    // ---------------------- 消息处理逻辑 ----------------------
    socket.on('private_message', async ({ to, message, from }) => {
        console.log(`收到消息：${from} -> ${to}，内容：${message}`);

        // 检查目标用户是否在线
        const targetSocketId = userSockets.get(to);
     
            // 生成时间戳
            const timestamp = new Date().toISOString();

            // 发送消息给目标用户
            socket.to(targetSocketId).emit('private_message', {
                from,
                message,
                timestamp,
                type: 'text'
            });

            // 存储聊天记录到数据库
            try {
                const newChatRecord = new chatRecordModel({
                    from,
                    to,
                    message,
                    timestamp
                });
                await newChatRecord.save();
            } catch (error) {
                console.error('保存聊天记录失败:', error);
            }

            // 存储聊天记录（按对话对存储）
            const conversationKey = [from, to].sort().join('-');
            if (!chatHistory.has(conversationKey)) {
                chatHistory.set(conversationKey, []);
            }
            chatHistory.get(conversationKey).push({ from, message, timestamp });

            console.log(`消息已送达 ${to}（Socket: ${targetSocketId}`);
     
    });

    // ---------------------- 断开连接处理 ----------------------
    socket.on('disconnect', () => {
        // 根据Socket ID查找并删除用户映射
        const userId = [...userSockets.entries()].find(([id, socketId]) => socketId === socket.id)?.[0];
        userId && userSockets.delete(userId);
        console.log(`用户 ${userId || '未登录用户'} 断开连接，Socket ID: ${socket.id}`);
    });

    // ---------------------- 获取聊天历史记录 ----------------------
    socket.on('get_chat_history', async ({ from, to }) => {
        try {
            const conversationKey = [from, to].sort().join('-');
            const chatRecords = await chatRecordModel.find({
                $or: [
                    { from, to },
                    { from: to, to: from }
                ]
            }).sort({ timestamp: 1 });

            socket.emit('chat_history', {
                conversationKey,
                messages: chatRecords
            });
        } catch (error) {
            console.error('获取聊天历史记录失败:', error);
        }
    });
});






